package cn.yazy.集合.set;

import java.util.HashSet;

/**
 *@author ZhangAJ:
 *@version 创建时间：2022年11月7日下午3:51:58
 */
public class HashSetDemo2 {
    public static void main(String[] args) {
        // 创建 HashSet 对象
        HashSet<Student> hs = new HashSet<Student>();
        // 给集合中添加自定义对象
        hs.add(new Student("张三",12));
        hs.add(new Student("李四",18));
        hs.add(new Student("王五",19));
        hs.add(new Student("张三",14));
        System.out.println(hs);
    }
}

class Student{
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        System.out.println(result);
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
        //备注：给HashSet中存放自定义类型元素时，需要重写对象中的hashCode和equals方法，
        //建立自己的比较方式，才能保证HashSet集合中的对象唯一。
    }
}